<template>
 <div class="createPost-container">
    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="21">
            <el-form-item style="margin-bottom: 40px;" prop="name">
              <MDinput name="name" v-model="postForm.name" :maxlength="20">
                角色名称
              </MDinput>
             </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-bottom: 40px;" label-width="74px" label="简单描述:">
          <el-input type="textarea" class="article-textarea" :rows="1" autosize placeholder="请输入内容" v-model="postForm.describe" style="width: 87%"></el-input>
          <span class="word-counter" v-show="describeLength">{{describeLength}}字</span>
        </el-form-item>
        <el-form-item style="margin-bottom: 40px;" label-width="74px" label="等级:">
          <el-input type="number" :min="1" step="1" :max="10" placeholder="数越大,等级越小" v-model="postForm.level" style="width: 87%"></el-input>
        </el-form-item>
        <!-- <el-row>
          <el-col :span="21">
            <el-form-item style="margin-bottom: 40px;" label-width="105px" label="权限路由分配:">
                <el-tree :data="permissTree"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :default-checked-keys="permission_arr" 
                  ref="roleTree"  
                  highlight-current  
                  :props="roleProps">
                  </el-tree>  
             </el-form-item>
          </el-col>
        </el-row> -->
        <!-- // 权限重构 -->
        <el-row>
          <el-col :span="21">
              <role-tree :data="permissTree" :columns="columns" border @dataIds="dataIds"></role-tree>
          </el-col>
        </el-row>
        <!-- // 权限重构 -->
        
       <!-- // 提交 -->
        <el-form-item style="margin-bottom: 40px;" label-width="180px" >
          <el-button type="primary"  :loading="loading" @click.stop="submitForm()">立即提交</el-button>
          <!-- <el-button type="primary" plain @click="resetChecked">清空</el-button> -->
        </el-form-item>
      </div>
    </el-form>
  </div>


</template>
<script>
import MDinput from '@/components/MDinput'
import { mapGetters } from 'vuex'
import * as api from '@/api/main-api' // API
import roleTree from '@/components/TreeTable/roleTree'
//   isIndeterminate属性是控制多选半选中状态，
//   checkAll是控制全选中状态
//   selectchecked是放置sonData1选中项
export default {
  name: 'editRole',

  components: { MDinput, roleTree },

  data() {
    return {
      columns: [
        {
          text: '菜单列表',
          value: 'name',
          width: 200,
          option: 'sonData'
        },
        {
          text: '功能权限',
          value: 'sonData',
          option: 'sonData',
          act: 'act'
        }
      ],
      postForm: {
        name: '', // 题目
        describe: ''
      },
      loading: false,
      permissTree: [], // 权限树状图
      // permission_arr: [], // 默认选中id
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }]
      },
      roleid: 0,
      permissionIds: []

      // 默认字段名称
      // roleProps: {
      //   children: 'children',
      //   label: 'name'
      // }

    }
  },

  computed: {
    // 从 vuex 去除数据
    ...mapGetters([
      'roles_info'
    ]),
    describeLength() {
      return this.postForm.describe.length
    }
  },

  created() {
    // 传过来的数据
    if (this.$route.query.es === 'edit') {
      if (this.roles_info) {
        this.postForm = this.roles_info
        // this.permission_arr = this.roles_info.permission_ids
        this.roleid = this.roles_info.id
      }
    }
    this.fetchTreeData(this.roleid)
  },

  methods: {
    dataIds(data) {
      let opt = []
      data.forEach(val => {
        opt.push(val.id)
        if (val.children) {
          val.children.forEach(el => {
            if (el.selectchecked.length) {
              opt.push(el.id)
              opt.push(el.selectchecked)
            }
          })
        }
      })
      opt = opt.join().split(',').filter(n => { return n })
      this.permissionIds = opt
    },

    // 表单提交
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          // var role_ids = this.$refs.roleTree.getCheckedKeys()
          if (this.permissionIds.length > 0) {
            this.postForm.permission_ids = this.permissionIds.join(',')
          } else {
            this.postForm.permission_ids = ''
          }
          this.postDataUrl(this.postForm)
        } else {
          console.log('error submit!!')
          this.loading = false
          return false
        }
      })
    },

    // 提交数据
    postDataUrl(data) {
      api.editRoleApi(data).then(response => {
        if (response.data.code === 0) {
          this.$root.message('操作成功', 'success')
          setTimeout(() => {
            this.$router.push({ path: '/permission/permission-role' })
          }, 20)
        }
      })
      this.loading = false
    },

    // 获取树状图数据
    fetchTreeData(roleid) {
      return new Promise((resolve, reject) => {
        api.permissionTreeApi({ 'role_id': roleid }).then(response => {
          if (response.data.code === 0) {
            this.permissTree = response.data.data
          }
        })
      })
    }

    // 清空选择
    // resetChecked() {
    //   this.$refs.roleTree.setCheckedKeys([])
    // }

  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/mixin.scss";
  .title-prompt{
    position: absolute;
    right: 0px;
    font-size: 12px;
    top:10px;
    color:#ff4949;
  }
  .createPost-container {
    position: relative;
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
        .postInfo-container-item {
          float: left;
        }
      }
      .editor-container {
        min-height: 500px;
        margin: 0 0 30px;
        .editor-upload-btn-container {
            text-align: right;
            margin-right: 10px;
            .editor-upload-btn {
                display: inline-block;
            }
        }
      }
    }
    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }
</style>
